package com.ss.project.xia17user.config.security.form;


import com.ss.project.xia17user.config.security.SecurityConfig;
import com.ss.project.xia17user.dao.entity.User;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * Form 认证提供
 * @author xia17
 * @date 2020/6/21
 */
@RequiredArgsConstructor
public class FormAuthenticationProvider implements AuthenticationProvider {

    private final UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        FormAuthentication formAuthentication = (FormAuthentication) authentication;
        UserDetails userDetails = userDetailsService.loadUserByUsername(authentication.getName());
        if (userDetails == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        Object credentials = authentication.getCredentials();
        String password = userDetails.getPassword();
        if (!SecurityConfig.PASSWORD_ENCODER.matches(credentials.toString(),password)){
            throw new BadCredentialsException("密码错误");
        }
        formAuthentication.setAuthenticated(true);
        formAuthentication.setUser((User) userDetails);
        return formAuthentication;
    }

    @Override
    public boolean supports(Class<?> clz) {
        return clz == FormAuthentication.class;
    }
}
